package com.david.func_test.view

import android.content.Context
import android.util.AttributeSet

/**
 * 左右排列的文本，需要左边文本自动伸缩，且左边文本过长时缩略
 */
class LimitLengthTextView(context: Context, attrs: AttributeSet): androidx.appcompat.widget.AppCompatTextView(context, attrs) {
    private var charWidth = 0f
    /**
     * 设置文本
     * @param autoStr 当文本太长时自动缩略
     * @param endStr 不缩放的右边文字
     */
    fun setText(autoStr: String, endStr: String) {
        val width = paint.measureText("$autoStr  $endStr")
        if (width > (measuredWidth - paddingLeft - paddingRight)) {
            if (charWidth == 0f) {
                charWidth = paint.measureText("正")
            }

            val moreWidth = width - (measuredWidth - paddingLeft - paddingRight)

            val removeCharNum = (moreWidth/charWidth).toInt() + 3

            if (autoStr.length > removeCharNum) {
                super.setText("${autoStr.substring(0, autoStr.length - removeCharNum)}...  $endStr")
            } else {
                super.setText("$autoStr  $endStr")
            }
        } else {
            super.setText("$autoStr  $endStr")
        }
    }
}